package com.yunwaikeji.gy_tool_library.adapter;

import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;

import java.util.Arrays;
import java.util.List;

public class GYFragmentPagerAdapter extends FragmentPagerAdapter {
    private List<Fragment> fragmentList;
    private List<String> titleList;
    private FragmentManager fragmentManager;

    public GYFragmentPagerAdapter(@NonNull FragmentManager fm, Fragment... fragments) {
        this(fm, Arrays.asList(fragments));
    }

    public GYFragmentPagerAdapter(@NonNull FragmentManager fm, List<Fragment> fragmentList) {
        this(fm, fragmentList, "");
    }

    public GYFragmentPagerAdapter(@NonNull FragmentManager fm, List<Fragment> fragmentList, String... titles) {
        this(fm, fragmentList, Arrays.asList(titles));
    }

    public GYFragmentPagerAdapter(@NonNull FragmentManager fragmentManager, List<Fragment> fragmentList, List<String> titleList) {
        super(fragmentManager);
        this.fragmentManager = fragmentManager;
        this.fragmentList = fragmentList;
        this.titleList = titleList;
    }

    @NonNull
    @Override
    public Fragment getItem(int position) {
        if (fragmentList != null && position < fragmentList.size()) {
            return fragmentList.get(position);
        }
        return null;
    }

    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {
        Fragment fragment = getItem(position);
        if (!fragment.isAdded()) { // 如果fragment还没有added
            FragmentTransaction ft = fragmentManager.beginTransaction();
            ft.add(fragment, fragment.getClass().getSimpleName());
            ft.commit();
            fragmentManager.executePendingTransactions();//同步的方式添加Fragment
        }

        if (fragment.getView().getParent() == null) {
            container.addView(fragment.getView()); // 为viewpager增加布局
        }
        return fragment;
    }

    @Override
    public int getCount() {
        return fragmentList == null ? 0 : fragmentList.size();
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        container.removeView(((Fragment) object).getView()); // 移出viewpager两边之外的page布局
    }

    @Nullable
    @Override
    public CharSequence getPageTitle(int position) {
        if (titleList != null && position < titleList.size()) {
            return titleList.get(position);
        }
        return super.getPageTitle(position);
    }

}
